<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import { getCodeTable, updateCodeTable } from '@/service/api/dev/code/code-table';
import CodeTableConfigForm from '../components/code-table-config-form.vue';
import CodeColumnConfigForm from '../components/code-column-config-form.vue';
import CodeUiConfigForm from '../components/code-ui-config-form.vue';
defineOptions({
  name: 'CodeTableEditDrawer'
});

interface Props {
  /** the edit row data */
  rowData?: Api.Model | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { validate, restoreValidation } = useNaiveForm();
const title = computed(() => {
  return '编辑生成配置';
});

const submitting = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const form = ref<Api.Dev.CodeGenRes>({
  table: { id: 0 },
  columns: []
});

async function handleInitModel() {
  const data = await getCodeTable(props.rowData?.id as number);
  form.value = data;
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  submitting.value = true;
  await validate();
  // request
  await updateCodeTable(form.value);
  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
  submitting.value = false;
}

watch(visible, () => {
  if (visible.value) {
    restoreValidation();
    handleInitModel();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" width="100%">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NTabs default-value="tableConfig">
        <NTabPane name="tableConfig" tab="基础配置">
          <CodeTableConfigForm :table="form.table"></CodeTableConfigForm>
        </NTabPane>
        <NTabPane name="columnConfig" tab="字段配置">
          <CodeColumnConfigForm :columns="form.columns"></CodeColumnConfigForm>
        </NTabPane>
        <NTabPane name="uiConfig" tab="界面配置">
          <CodeUiConfigForm :table="form.table"></CodeUiConfigForm>
        </NTabPane>
      </NTabs>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" :loading="submitting" @click="handleSubmit">保存</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
